//
// Copyright (c) 2009-2011, chunquedong
//
// This file is part of ChunMap project
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE(Version >=3)
//
// History:
//   2011-10-29  Jed Young  Creation
//

using fwt
using gfx
using array

using chunmapModel

class LineTool : Tool
{
  protected Bool draging := false

  Color color := Color.black
  protected CoordSeqBuf lse := CoordSeqBuf()
  |Geometry|? onCreateFinish

  override Void actionEvent(Event e)
  {
    switch (e.id)
    {
      case EventId.mouseDown:
        if (e.button != 3) mousePressed(e)
      case EventId.mouseUp:
        if (e.count == 2) mouseReleased(e)
      case EventId.mouseMove: mouseMove(e)
      default: return
    }
  }

  protected virtual Void mouseMove(Event e)
  {
    if (!draging) return

    map.paintOnBuffer |g|
    {
      map.drawOriginImage(g, 0, 0)
      g.drawPolyline2(toIntArray(e.pos.x, e.pos.y))
    }
    e.consume
    map.repaint
  }

  protected virtual Array toIntArray(Int x, Int y)
  {
    ps := Array.allocate((lse.size+1) * 2)
    n := lse.size
    i:=0

    for (; i<n; ++i)
    {
      p := lse.get(i)
      ps.setInt(i*2, map.view.x2Screen(p.x).toInt)
      ps.setInt((i*2)+1, map.view.y2Screen(p.y).toInt)
    }
    k := n*2
    ps.setInt(k, x)
    ps.setInt(k+1, y)
    return ps
  }

  private Void mousePressed(Event e)
  {
    draging = true
    x := e.pos.x
    y := e.pos.y
    lse.add(map.view.screen2World.call(Coord(x.toFloat, y.toFloat)))
  }

  private Void mouseReleased(Event e) {
    if (draging)
    {
      // reset
      draging = false

      lse.deleteOverPoint
      finished(lse)
      lse = CoordSeqBuf()
    }
  }

  protected virtual Void finished(CoordSeqBuf lse)
  {
    if (lse.size > 1)
    {
      ls := LineString(lse.toCoordSeq)
      onCreateFinish?.call(ls)
    }
  }
}